<template>
	<view class="map-container">
		<!-- 头部导航 -->
		<view class="header">
			<view class="header-left">
				<text class="back-btn" @click="goBack">←</text>
			</view>
			<view class="header-center">
				<text class="header-title">港口地图</text>
			</view>
			<view class="header-right">
				<text class="location-btn" @click="getCurrentLocation">📍</text>
			</view>
		</view>

		<!-- 地图主体区域 -->
		<view class="map-content">
			<!-- 地图组件 -->
			<AMapComponent 
				ref="mapRef"
				v-model:center="mapCenter"
				v-model:scale="mapScale"
				:markers="mapMarkers"
				:show-location="true"
				@map-ready="onMapReady"
				@location-change="onLocationChange"
				@marker-tap="onMarkerTap"
				@map-error="handleMapError"
			/>
			
			<!-- 地图加载遮罩 -->
			<view v-if="isMapLoading" class="map-loading-overlay">
				<view class="loading-spinner"></view>
				<text class="map-tip">地图加载中...</text>
			</view>
			
			<!-- 地图加载失败时的备用界面 -->
			<view v-if="mapLoadError" class="map-error-overlay">
				<view class="error-icon">⚠️</view>
				<text class="error-tip">地图加载失败</text>
				<button class="retry-btn" @click="retryLoadMap">重试</button>
			</view>

			<!-- 搜索框 -->
			<view class="search-overlay">
				<view class="search-container">
					<text class="search-icon">🔍</text>
					<input 
						class="search-input" 
						placeholder="搜索港口、城市..."
						v-model="searchText"
						@input="onSearchInput"
					/>
					<text v-if="searchText" class="clear-btn" @click="clearSearch">×</text>
				</view>
			</view>

			<!-- 功能按钮组 -->
			<view class="function-buttons">
				<view class="function-btn" @click="showAllPorts">
					<text class="btn-icon">🌍</text>
					<text class="btn-text">所有港口</text>
				</view>
				<view class="function-btn" @click="showNearbyPorts">
					<text class="btn-icon">🚢</text>
					<text class="btn-text">附近港口</text>
				</view>
				<view class="function-btn" @click="showFavorites">
					<text class="btn-icon">⭐</text>
					<text class="btn-text">收藏港口</text>
				</view>
			</view>
		</view>

		<!-- 底部信息卡片 -->
		<view class="info-card" v-if="selectedPort">
			<view class="card-header">
				<text class="port-name">{{ selectedPort.name }}</text>
				<text class="port-country">{{ selectedPort.country }}</text>
			</view>
			<view class="card-content">
				<text class="port-info">{{ selectedPort.description }}</text>
			</view>
			<view class="card-actions">
				<view class="action-btn primary" @click="selectThisPort">
					<text class="action-text">选择此港口</text>
				</view>
				<view class="action-btn secondary" @click="viewPortDetails">
					<text class="action-text">查看详情</text>
				</view>
			</view>
		</view>

		<!-- 附近港口弹框 -->
		<view class="nearby-ports-modal" v-if="showNearbyModal" @click="hideNearbyPorts">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">附近港口</text>
					<text class="close-btn" @click="hideNearbyPorts">×</text>
				</view>
				<view class="modal-body">
					<!-- 港口列表 -->
					<view class="port-item" v-for="port in nearbyPorts" :key="port.id">
						<view class="port-info" @click="selectNearbyPort(port)">
							<view class="port-main">
								<text class="port-name">{{ port.name }}</text>
								<text class="port-distance" v-if="port.distance">{{ port.distance }}km</text>
							</view>
							<text class="port-description">{{ port.description || port.portCode || port.countryName || '港口信息' }}</text>
						</view>
						<view class="port-actions">
							<view class="favorite-btn" :class="{ active: port.isFavorited }" @click.stop="toggleFavorite(port)">
								<text class="favorite-icon">{{ port.isFavorited ? '⭐' : '☆' }}</text>
							</view>
							<text class="port-arrow" @click.stop="selectNearbyPort(port)">→</text>
						</view>
					</view>
					
					<!-- 加载状态 -->
					<view class="empty-state" v-if="isLoadingNearbyPorts">
						<text class="empty-icon">🔄</text>
						<text class="empty-text">正在获取附近港口...</text>
						<text class="empty-desc">请稍等片刻</text>
					</view>
					
					<!-- 空状态 -->
					<view class="empty-state" v-else-if="!isLoadingNearbyPorts && nearbyPorts.length === 0">
						<text class="empty-icon">🏗️</text>
						<text class="empty-text">附近暂无港口</text>
						<text class="empty-desc">尝试扩大搜索范围</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 收藏港口弹框 -->
		<view class="favorites-modal" v-if="showFavoritesModal" @click="hideFavorites">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">收藏港口</text>
					<text class="close-btn" @click="hideFavorites">×</text>
				</view>
				<view class="modal-body">
					<!-- 收藏港口列表 -->
					<view class="port-item" v-for="port in favoritePorts" :key="port.id">
						<view class="port-info" @click="selectFavoritePort(port)">
							<view class="port-main">
								<text class="port-name">{{ port.name }}</text>
								<text class="port-distance" v-if="port.distance">{{ port.distance }}km</text>
							</view>
							<text class="port-description">{{ port.description || port.portCode }}</text>
						</view>
						<view class="port-actions">
							<view class="favorite-btn active" @click.stop="removeFavorite(port)">
								<text class="favorite-icon">⭐</text>
							</view>
							<text class="port-arrow" @click.stop="selectFavoritePort(port)">→</text>
						</view>
					</view>
					
					<!-- 空状态 -->
					<view class="empty-state" v-if="favoritePorts.length === 0">
						<text class="empty-icon">💫</text>
						<text class="empty-text">暂无收藏港口</text>
						<text class="empty-desc">去地图上收藏喜欢的港口吧</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, inject } from 'vue'
import { portApi } from '@/api/port.js'
import { getCurrentUserId } from '@/utils/userAuth.js'
import AMapComponent from '@/components/AMapComponent.vue'

// 全局状态
const store = inject('$store')

// 响应式数据
const searchText = ref('')
const selectedPort = ref(null)
const showNearbyModal = ref(false)
const isMapLoading = ref(true)
const mapLoadError = ref(false)
const currentPosition = ref(null)
const mapRef = ref(null)

// 地图相关数据
const mapCenter = ref({
	latitude: 39.90923,
	longitude: 116.397428
})
const mapScale = ref(13)
const mapMarkers = ref([])

// 港口数据将通过API获取

// 附近港口数据
const nearbyPorts = ref([])
const isLoadingNearbyPorts = ref(false)

// 收藏港口数据
const favoritePorts = ref([])
const showFavoritesModal = ref(false)

// 所有港口数据
const allPorts = ref([])
const isLoadingAllPorts = ref(false)

// 方法定义
const goBack = () => {
	uni.navigateBack()
}

const getCurrentLocation = async () => {
	try {
		console.log('开始获取位置...')
		uni.showLoading({
			title: '正在定位...'
		})
		
		if (mapRef.value) {
			const position = await mapRef.value.getCurrentLocation()
			console.log('获取到位置:', position)
			currentPosition.value = position
			
			// 强制设置地图中心到当前位置
			mapCenter.value = {
				latitude: position.latitude,
				longitude: position.longitude
			}
			mapScale.value = 16 // 增加缩放级别，更清楚地显示位置
			
			// 使用绿色圆点作为当前位置标记
			const locationMarker = {
				id: 'current-location',
				latitude: position.latitude,
				longitude: position.longitude,
				title: '我的位置',
				width: 40,
				height: 40,
				iconPath: '/static/images/c6cdbd50bfd89f8e4280e2893e323bbd.png', // 使用现有的图片作为测试
				callout: {
					content: '🔵 我的位置',
					color: '#FFFFFF',
					bgColor: '#4CAF50',
					fontSize: 12,
					borderRadius: 5,
					padding: 3,
					display: 'ALWAYS'
				}
			}
			
			console.log('创建位置标记:', locationMarker)
			
			// 清空之前的标记，添加当前位置标记
			mapMarkers.value = [locationMarker]
			console.log('当前标记列表:', mapMarkers.value)
			
			uni.hideLoading()
			uni.showToast({
				title: '定位成功',
				icon: 'success'
			})
			
			// 先获取附近港口，然后再移动地图位置
			await loadNearbyPorts(position.longitude, position.latitude)
			
			// 延迟一下确保地图更新（在港口加载完成后）
			setTimeout(() => {
				// 再次确保地图中心位置正确
				if (mapRef.value && mapRef.value.moveToLocation) {
					mapRef.value.moveToLocation({
						latitude: position.latitude,
						longitude: position.longitude
					})
				}
				console.log('最终标记列表:', mapMarkers.value)
			}, 1000)
		} else {
			throw new Error('地图未初始化，请稍后再试')
		}
	} catch (error) {
		console.error('定位失败:', error)
		uni.hideLoading()
		
		let errorMessage = '定位失败'
		if (error.message) {
			errorMessage = error.message
		} else if (error.code) {
			switch (error.code) {
				case 1:
					errorMessage = '用户拒绝了定位请求'
					break
				case 2:
					errorMessage = '位置信息不可用'
					break
				case 3:
					errorMessage = '定位超时'
					break
				default:
					errorMessage = '定位服务异常'
			}
		}
		
		uni.showToast({
			title: errorMessage,
			icon: 'none',
			duration: 3000
		})
		
		// 定位失败时使用默认位置（上海）
		const defaultPosition = {
			latitude: 31.2304,
			longitude: 121.4737
		}
		
		mapCenter.value = {
			latitude: defaultPosition.latitude,
			longitude: defaultPosition.longitude
		}
		mapScale.value = 12
	}
}

const onSearchInput = async () => {
	// 实时搜索逻辑
	if (searchText.value.trim()) {
		try {
			// 调用后端搜索接口
			const response = await portApi.searchPorts(searchText.value.trim())
			console.log('搜索结果:', response.data)
			
			// 如果有搜索结果，在地图上显示
			if (response.data && response.data.length > 0) {
				const searchMarkers = response.data.map((port, index) => ({
					id: `search-${index}`,
					latitude: port.latitude,
					longitude: port.longitude,
					title: port.name,
					iconPath: '/static/port-icon.png',
					width: 25,
					height: 25
				}))
				
				// 保留当前位置标记，添加搜索结果标记
				const currentMarkers = mapMarkers.value.filter(m => m.id === 'current-location')
				mapMarkers.value = [...currentMarkers, ...searchMarkers]
				
				// 将地图中心设置到第一个结果
				mapCenter.value = {
					latitude: response.data[0].latitude,
					longitude: response.data[0].longitude
				}
				mapScale.value = 13
			}
			
		} catch (error) {
			console.error('搜索失败:', error)
		}
			} else {
			// 清空搜索时恢复到当前位置
			if (currentPosition.value) {
				mapCenter.value = {
					latitude: currentPosition.value.latitude,
					longitude: currentPosition.value.longitude
				}
				// 恢复用户位置标记
				const currentMarkers = mapMarkers.value.filter(m => m.id === 'current-location')
				mapMarkers.value = currentMarkers
			} else {
				mapMarkers.value = []
			}
		}
}

const clearSearch = () => {
	searchText.value = ''
}

const showAllPorts = async () => {
	try {
		console.log('开始加载所有港口')
		isLoadingAllPorts.value = true
		uni.showLoading({
			title: '加载港口中...'
		})
		
		// 调用新的API获取所有港口位置
		const response = await uni.request({
			url: '/user/map/ports-locations',
			method: 'GET',
			header: {
				'Content-Type': 'application/json'
			}
		})
		
		console.log('所有港口响应:', response)
		
		if (response.statusCode === 200 && response.data.code === 200) {
			allPorts.value = response.data.data || []
			
			// 在地图上显示所有港口标记
			if (allPorts.value.length > 0) {
				const portMarkers = allPorts.value.map((port) => ({
					id: `all-port-${port.id}`,
					latitude: port.latitude,
					longitude: port.longitude,
					title: `🚢 ${port.name}`,
					iconPath: '/static/images/c6cdbd50bfd89f8e4280e2893e323bbd.png',
					width: 25,
					height: 25,
					callout: {
						content: `${port.name}${port.countryName ? ' (' + port.countryName + ')' : ''}`,
						color: '#FFFFFF',
						bgColor: '#2196F3',
						fontSize: 12,
						borderRadius: 5,
						padding: 3,
						display: 'BYCLICK'
					}
				}))
				
				// 保留当前位置标记，添加所有港口标记
				const currentMarkers = mapMarkers.value.filter(m => m.id === 'current-location')
				mapMarkers.value = [...currentMarkers, ...portMarkers]
				
				console.log(`成功在地图上标记了${portMarkers.length}个港口`)
				
				// 如果有当前位置，计算距离
				if (currentPosition.value) {
					allPorts.value.forEach(port => {
						const distance = calculateDistance(
							currentPosition.value.latitude,
							currentPosition.value.longitude,
							port.latitude,
							port.longitude
						)
						port.distance = Math.round(distance * 100) / 100
					})
					
					// 按距离排序
					allPorts.value.sort((a, b) => (a.distance || 999999) - (b.distance || 999999))
				}
				
				uni.showToast({
					title: `已标记${allPorts.value.length}个港口`,
					icon: 'success'
				})
			} else {
				uni.showToast({
					title: '暂无港口数据',
					icon: 'none'
				})
			}
		} else {
			throw new Error(response.data?.message || '获取港口数据失败')
		}
		
	} catch (error) {
		console.error('加载所有港口失败:', error)
		uni.showToast({
			title: '加载港口失败，请重试',
			icon: 'none'
		})
	} finally {
		isLoadingAllPorts.value = false
		uni.hideLoading()
	}
}

const showNearbyPorts = async () => {
	showNearbyModal.value = true
	
	// 先加载收藏港口数据，确保收藏状态正确
	await loadFavoritePorts()
	
	// 显示弹框时加载附近港口数据
	if (currentPosition.value) {
		// 如果有当前位置，使用当前位置
		await loadNearbyPorts(currentPosition.value.longitude, currentPosition.value.latitude)
	} else {
		// 如果没有当前位置，先获取位置
		try {
			await getCurrentLocation()
			if (currentPosition.value) {
				await loadNearbyPorts(currentPosition.value.longitude, currentPosition.value.latitude)
			}
		} catch (error) {
			console.error('获取位置失败:', error)
			uni.showToast({
				title: '请先获取当前位置',
				icon: 'none'
			})
		}
	}
}

const hideNearbyPorts = () => {
	showNearbyModal.value = false
}

const selectNearbyPort = (port) => {
	// 设置选中的港口，保持完整的港口信息
	selectedPort.value = {
		id: port.id,
		name: port.name,
		code: port.portCode || port.code,
		country: port.countryName || port.country || '未知',
		description: port.description || '港口信息',
		latitude: port.latitude,
		longitude: port.longitude,
		distance: port.distance
	}
	
	hideNearbyPorts()
	
	// 将地图中心移动到选中的港口
	mapCenter.value = {
		latitude: port.latitude,
		longitude: port.longitude
	}
	mapScale.value = 15
	
	uni.showToast({
		title: `已选中${port.name}`,
		icon: 'success'
	})
}



const showFavorites = () => {
	showFavoritesModal.value = true
	// 显示弹框时加载收藏港口数据
	loadFavoritePorts()
}

const hideFavorites = () => {
	showFavoritesModal.value = false
}

const selectFavoritePort = (port) => {
	// 设置选中的港口，确保数据格式完整
	selectedPort.value = {
		id: port.id,
		name: port.name,
		code: port.portCode || port.code,
		country: port.countryName || port.country || '未知',
		description: port.description || '港口信息',
		latitude: port.latitude,
		longitude: port.longitude,
		distance: port.distance
	}
	
	showFavoritesModal.value = false
	
	// 将地图中心移动到选中的港口
	if (port.latitude && port.longitude) {
		mapCenter.value = {
			latitude: port.latitude,
			longitude: port.longitude
		}
		mapScale.value = 15
	}
	
	uni.showToast({
		title: `已选中${port.name}`,
		icon: 'success'
	})
}

const removeFavorite = async (port) => {
	try {
		const userId = getCurrentUserId()
		if (!userId) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			return
		}

		const response = await portApi.togglePortFavorite(userId, port.id)
		
		if (response.code === 200) {
			// 从收藏列表中移除
			const index = favoritePorts.value.findIndex(p => p.id === port.id)
			if (index !== -1) {
				favoritePorts.value.splice(index, 1)
			}
			
			// 更新附近港口列表中的收藏状态
			const nearbyIndex = nearbyPorts.value.findIndex(p => p.id === port.id)
			if (nearbyIndex !== -1) {
				nearbyPorts.value[nearbyIndex].isFavorited = false
			}
			
			uni.showToast({
				title: response.data.message,
				icon: 'success'
			})
		} else {
			uni.showToast({
				title: response.message || '操作失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('取消收藏失败:', error)
		uni.showToast({
			title: '操作失败，请重试',
			icon: 'none'
		})
	}
}

const toggleFavorite = async (port) => {
	try {
		const userId = getCurrentUserId()
		if (!userId) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			return
		}

		const response = await portApi.togglePortFavorite(userId, port.id)
		
		if (response.code === 200) {
			// 更新本地状态
			port.isFavorited = response.data.isFavorited
			
			// 更新附近港口列表中的收藏状态
			const nearbyIndex = nearbyPorts.value.findIndex(p => p.id === port.id)
			if (nearbyIndex !== -1) {
				nearbyPorts.value[nearbyIndex].isFavorited = response.data.isFavorited
			}
			
			// 更新收藏港口列表
			const favoriteIndex = favoritePorts.value.findIndex(p => p.id === port.id)
			if (response.data.isFavorited) {
				if (favoriteIndex === -1) {
					favoritePorts.value.push({ ...port, isFavorited: true })
				}
			} else {
				if (favoriteIndex !== -1) {
					favoritePorts.value.splice(favoriteIndex, 1)
				}
			}
			
			uni.showToast({
				title: response.data.message,
				icon: 'success'
			})
		} else {
			uni.showToast({
				title: response.message || '操作失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('收藏操作失败:', error)
		uni.showToast({
			title: '操作失败，请重试',
			icon: 'none'
		})
	}
}

// 地图准备就绪
const onMapReady = (mapInstance) => {
	console.log('地图初始化成功', mapInstance)
	isMapLoading.value = false
	
	// 地图初始化完成后立即获取当前位置
	nextTick(() => {
		getCurrentLocation()
	})
}

// 地图加载错误处理
const handleMapError = (error) => {
	console.error('地图加载错误:', error)
	isMapLoading.value = false
	mapLoadError.value = true
	uni.showToast({
		title: '地图加载失败',
		icon: 'none'
	})
}

// 重试加载地图
const retryLoadMap = () => {
	isMapLoading.value = true
	mapLoadError.value = false
	// 重新初始化地图组件
	nextTick(() => {
		if (mapRef.value) {
			// 触发地图组件重新初始化
			console.log('重试加载地图')
		}
	})
}

// 地图位置改变
const onLocationChange = (location) => {
	console.log('地图位置改变:', location)
	mapCenter.value = {
		latitude: location.latitude,
		longitude: location.longitude
	}
	mapScale.value = location.scale
}

// 标记点击事件
const onMarkerTap = (e) => {
	console.log('标记点击:', e)
	const markerId = e.detail.markerId
	const marker = mapMarkers.value.find(m => m.id === markerId)
	
	if (marker && markerId !== 'current-location') {
		// 查找对应的港口数据
		let portData = null
		
		// 从附近港口中查找
		if (markerId.startsWith('port-')) {
			const portId = markerId.replace('port-', '')
			portData = nearbyPorts.value.find(p => p.id == portId)
		}
		
		// 从所有港口中查找
		if (!portData && markerId.startsWith('all-port-')) {
			const portId = markerId.replace('all-port-', '')
			portData = allPorts.value.find(p => p.id == portId)
		}
		
		if (portData) {
			// 设置选中的港口
			selectedPort.value = {
				id: portData.id,
				name: portData.name,
				code: portData.portCode || portData.code,
				country: portData.countryName || portData.country || '未知',
				description: portData.description || '港口信息',
				latitude: portData.latitude,
				longitude: portData.longitude,
				distance: portData.distance
			}
			
			console.log('选中港口:', selectedPort.value)
			
			uni.showToast({
				title: `已选中${portData.name}`,
				icon: 'success'
			})
		} else {
			// 备用处理：显示标记信息
			uni.showModal({
				title: marker.title || '港口信息',
				content: `纬度: ${marker.latitude}\n经度: ${marker.longitude}`,
				showCancel: false
			})
		}
	}
}

// 加载附近港口
const loadNearbyPorts = async (longitude, latitude) => {
	try {
		console.log('开始加载附近港口:', { longitude, latitude })
		isLoadingNearbyPorts.value = true
		nearbyPorts.value = [] // 清空之前的数据
		
		const userId = getCurrentUserId()
		console.log('用户ID:', userId)
		
		// 尝试使用更简单的API端点
		try {
			const response = await uni.request({
				url: '/user/map/nearby-ports',
				method: 'GET',
				data: {
					latitude: latitude,
					longitude: longitude,
					limit: 50
				},
				header: {
					'Content-Type': 'application/json'
				}
			})
			
			console.log('附近港口响应:', response)
			
			if (response.statusCode === 200 && response.data.code === 200) {
				let portsList = response.data.data || []
				console.log('解析后的港口列表:', portsList)
				
				// 设置港口的收藏状态
				portsList.forEach(port => {
					const isFavorited = favoritePorts.value.some(favPort => favPort.id === port.id)
					port.isFavorited = isFavorited
				})
				
				nearbyPorts.value = portsList
				
				// 在地图上显示港口标记
				if (portsList.length > 0) {
					const portMarkers = portsList.map((port) => ({
						id: `port-${port.id}`,
						latitude: port.latitude,
						longitude: port.longitude,
						title: `🚢 ${port.name}`,
						iconPath: '/static/images/c6cdbd50bfd89f8e4280e2893e323bbd.png',
						width: 25,
						height: 25,
						callout: {
							content: `${port.name} (${port.distance}km)`,
							color: '#FFFFFF',
							bgColor: '#FF6B6B',
							fontSize: 12,
							borderRadius: 5,
							padding: 3,
							display: 'BYCLICK'
						}
					}))
					
					// 保留当前位置标记，添加港口标记
					const currentMarkers = mapMarkers.value.filter(m => m.id === 'current-location')
					mapMarkers.value = [...currentMarkers, ...portMarkers]
					console.log('加载港口后的标记列表:', mapMarkers.value)
					
					uni.showToast({
						title: `找到${portsList.length}个附近港口`,
						icon: 'success'
					})
				} else {
					uni.showToast({
						title: '附近暂无港口',
						icon: 'none'
					})
				}
			} else {
				throw new Error(response.data?.message || '获取港口数据失败')
			}
		} catch (apiError) {
			console.error('使用nearby-ports API失败，尝试fallback API:', apiError)
			
			// 如果第一个API失败，尝试原来的API
			const response = await portApi.getNearbyPorts(latitude, longitude, 100, userId)
			console.log('备用API响应:', response)
			
			// 处理响应格式
			let portsList = []
			if (response && response.code === 200 && response.data) {
				if (response.data.list && Array.isArray(response.data.list)) {
					portsList = response.data.list
				} else if (response.data.records && Array.isArray(response.data.records)) {
					portsList = response.data.records
				} else if (Array.isArray(response.data)) {
					portsList = response.data
				}
			} else if (response && Array.isArray(response)) {
				// 直接返回数组
				portsList = response
			}
			
			console.log('解析后的港口列表:', portsList)
			nearbyPorts.value = portsList
			
			// 在地图上显示港口标记
			if (portsList.length > 0) {
				const portMarkers = nearbyPorts.value.map((port, index) => ({
					id: `port-${port.id}`,
					latitude: port.latitude,
					longitude: port.longitude,
					title: `🚢 ${port.name}`,
					iconPath: '/static/images/c6cdbd50bfd89f8e4280e2893e323bbd.png',
					width: 25,
					height: 25,
					callout: {
						content: `${port.name}${port.distance ? ' (' + port.distance + 'km)' : ''}`,
						color: '#FFFFFF',
						bgColor: '#FF6B6B',
						fontSize: 12,
						borderRadius: 5,
						padding: 3,
						display: 'BYCLICK'
					}
				}))
				
				// 保留当前位置标记，添加港口标记
				const currentMarkers = mapMarkers.value.filter(m => m.id === 'current-location')
				mapMarkers.value = [...currentMarkers, ...portMarkers]
				console.log('加载港口后的标记列表:', mapMarkers.value)
			}
		}
		
	} catch (error) {
		console.error('获取附近港口失败:', error)
		nearbyPorts.value = []
		uni.showToast({
			title: '获取港口信息失败: ' + (error.message || '未知错误'),
			icon: 'none',
			duration: 3000
		})
	} finally {
		isLoadingNearbyPorts.value = false
	}
}

// 加载收藏港口
const loadFavoritePorts = async () => {
	try {
		const userId = getCurrentUserId()
		if (!userId) {
			console.log('用户未登录，无法加载收藏港口')
			return
		}

		const response = await portApi.getUserFavoritePorts(userId)
		
		if (response.code === 200 && response.data) {
			favoritePorts.value = response.data.list || []
		} else {
			favoritePorts.value = []
		}
		
		console.log('加载收藏港口:', favoritePorts.value)
	} catch (error) {
		console.error('加载收藏港口失败:', error)
		favoritePorts.value = []
	}
}

// 计算两点间距离的函数（Haversine公式）
const calculateDistance = (lat1, lng1, lat2, lng2) => {
	const EARTH_RADIUS = 6371.0 // 地球半径（公里）
	
	const latDistance = (lat2 - lat1) * Math.PI / 180
	const lngDistance = (lng2 - lng1) * Math.PI / 180
	
	const a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) +
		Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
		Math.sin(lngDistance / 2) * Math.sin(lngDistance / 2)
	
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
	
	return EARTH_RADIUS * c
}

// 生命周期钩子
onMounted(() => {
	// 地图组件会自动初始化
	isMapLoading.value = true
	
	// 设置地图加载超时
	setTimeout(() => {
		if (isMapLoading.value) {
			console.warn('地图加载超时')
			handleMapError(new Error('地图加载超时'))
		}
	}, 10000) // 10秒超时

	// 初始化收藏港口数据
	loadFavoritePorts()
	
	// 自动加载所有港口
	setTimeout(() => {
		showAllPorts()
	}, 2000) // 延迟2秒，确保地图已经初始化完成
})

onUnmounted(() => {
	// 地图组件会自动销毁
	mapMarkers.value = []
})

const selectThisPort = () => {
	if (!selectedPort.value) {
		uni.showToast({
			title: '请先选择一个港口',
			icon: 'none'
		})
		return
	}

	try {
		// 将选中的港口保存到全局状态
		store.actions.setSelectedPort(selectedPort.value)
		
		// 显示成功提示
		uni.showToast({
			title: `已选择${selectedPort.value.name}`,
			icon: 'success',
			duration: 1500
		})
		
		// 延迟跳转到主页面
		setTimeout(() => {
			uni.switchTab({
				url: '/pages/index/index'
			})
		}, 1500)
		
	} catch (error) {
		console.error('选择港口失败:', error)
		uni.showToast({
			title: '选择港口失败，请重试',
			icon: 'none'
		})
	}
}

const viewPortDetails = () => {
	uni.showToast({
		title: '港口详情功能开发中',
		icon: 'none'
	})
}




</script>

<style lang="scss" scoped>
.map-container {
	width: 100%;
	height: 100vh;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	position: relative;
	overflow: hidden;
}

.header {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	height: 88px;
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(20px);
	border-bottom: 1px solid rgba(255, 255, 255, 0.2);
	display: flex;
	align-items: flex-end;
	padding: 0 20px 12px;
	z-index: 1000;
	box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);

	.header-left,
	.header-right {
		width: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.header-center {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.back-btn,
	.location-btn {
		font-size: 20px;
		color: #333333;
		padding: 8px;
		border-radius: 50%;
		transition: all 0.2s ease;

		&:active {
			background: rgba(0, 0, 0, 0.1);
			transform: scale(0.9);
		}
	}

	.header-title {
		font-size: 18px;
		font-weight: 600;
		color: #333333;
		letter-spacing: 0.5px;
	}
}

.map-content {
	padding-top: 88px;
	height: 100%;
	position: relative;
}



.map-loading-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background: rgba(255, 255, 255, 0.9);
	z-index: 10;

	.loading-spinner {
		width: 40px;
		height: 40px;
		border: 3px solid #f3f3f3;
		border-top: 3px solid #007bff;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20px;
	}

	.map-tip {
		font-size: 16px;
		color: #666666;
		font-weight: 400;
	}
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.map-error-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background: rgba(255, 255, 255, 0.9);
	z-index: 10;

	.error-icon {
		font-size: 48px;
		margin-bottom: 16px;
	}

	.error-tip {
		font-size: 16px;
		color: #666666;
		font-weight: 400;
		margin-bottom: 20px;
	}

	.retry-btn {
		background: #007bff;
		border: none;
		border-radius: 4px;
		padding: 10px 20px;
		color: white;
		font-size: 14px;
		font-weight: 400;
		transition: background-color 0.2s ease;

		&:hover {
			background: #0056b3;
		}
	}
}



.search-overlay {
	position: absolute;
	top: 20px;
	left: 20px;
	right: 20px;
	z-index: 100;
}

.search-container {
	background: rgba(255, 255, 255, 0.95);
	border-radius: 25px;
	padding: 0 20px;
	display: flex;
	align-items: center;
	gap: 12px;
	height: 50px;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
	backdrop-filter: blur(10px);
	border: 1px solid rgba(255, 255, 255, 0.3);

	.search-icon {
		font-size: 18px;
		color: #6c757d;
	}

	.search-input {
		flex: 1;
		font-size: 16px;
		color: #333333;
		background: transparent;
		border: none;
		outline: none;

		&::placeholder {
			color: #8e9aaf;
		}
	}

	.clear-btn {
		font-size: 20px;
		color: #6c757d;
		padding: 5px;
		border-radius: 50%;
		transition: all 0.2s ease;

		&:active {
			background: rgba(108, 117, 125, 0.1);
			transform: scale(0.9);
		}
	}
}

.function-buttons {
	position: absolute;
	right: 20px;
	top: 90px;
	display: flex;
	flex-direction: column;
	gap: 12px;
	z-index: 100;
}

.function-btn {
	background: rgba(255, 255, 255, 0.95);
	border-radius: 15px;
	padding: 12px;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 4px;
	min-width: 70px;
	box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
	backdrop-filter: blur(10px);
	transition: all 0.2s ease;

	&:active {
		transform: scale(0.95);
		box-shadow: 0 1px 8px rgba(0, 0, 0, 0.15);
	}

	.btn-icon {
		font-size: 20px;
	}

	.btn-text {
		font-size: 12px;
		color: #333333;
		font-weight: 500;
	}
}

.info-card {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	background: rgba(255, 255, 255, 0.98);
	border-radius: 20px 20px 0 0;
	padding: 20px;
	backdrop-filter: blur(20px);
	box-shadow: 0 -4px 30px rgba(0, 0, 0, 0.15);
	animation: slideUp 0.3s ease-out;
	z-index: 200;
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}

.card-header {
	display: flex;
	align-items: center;
	gap: 12px;
	margin-bottom: 12px;

	.port-name {
		font-size: 20px;
		font-weight: 600;
		color: #333333;
	}

	.port-country {
		font-size: 14px;
		color: #6c757d;
		background: rgba(108, 117, 125, 0.1);
		padding: 4px 8px;
		border-radius: 8px;
	}
}

.card-content {
	margin-bottom: 20px;

	.port-info {
		font-size: 16px;
		color: #555555;
		line-height: 1.5;
	}
}

.card-actions {
	display: flex;
	gap: 12px;
}

.action-btn {
	flex: 1;
	padding: 12px 16px;
	border-radius: 12px;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.2s ease;

	&.primary {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

		.action-text {
			color: #ffffff;
			font-weight: 600;
		}

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2px 10px rgba(102, 126, 234, 0.4);
		}
	}

	&.secondary {
		background: rgba(108, 117, 125, 0.1);

		.action-text {
			color: #6c757d;
			font-weight: 500;
		}

		&:active {
			background: rgba(108, 117, 125, 0.2);
			transform: scale(0.98);
		}
	}

	.action-text {
		font-size: 16px;
	}
}

/* 附近港口弹框样式 */
.nearby-ports-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.6);
	display: flex;
	align-items: flex-end;
	justify-content: center;
	z-index: 300;
	animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
	from {
		opacity: 0;
	}
	to {
		opacity: 1;
	}
}

.modal-content {
	background: #ffffff;
	border-radius: 20px 20px 0 0;
	width: 100%;
	max-height: 70vh;
	overflow: hidden;
	box-shadow: 0 -10px 30px rgba(0, 0, 0, 0.2);
	animation: slideUpModal 0.3s ease-out;
}

@keyframes slideUpModal {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20px;
	border-bottom: 1px solid #eee;
	background: #f8f9fa;
}

.modal-title {
	font-size: 20px;
	font-weight: 600;
	color: #333333;
}

.close-btn {
	font-size: 28px;
	color: #6c757d;
	padding: 5px 8px;
	border-radius: 50%;
	transition: all 0.2s ease;
	line-height: 1;
	
	&:active {
		background: rgba(0, 0, 0, 0.05);
		transform: scale(0.9);
	}
}

.modal-body {
	padding: 0 20px 20px;
	max-height: calc(70vh - 80px);
	overflow-y: auto;
}

.port-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16px 0;
	border-bottom: 1px solid #f0f0f0;
	transition: all 0.2s ease;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: rgba(102, 126, 234, 0.05);
		transform: scale(0.98);
	}
	
	.port-info {
		flex: 1;
	}
	
	.port-main {
		display: flex;
		justify-content: space-between;
		align-items: baseline;
		margin-bottom: 6px;
	}
	
	.port-name {
		font-size: 17px;
		font-weight: 500;
		color: #333333;
	}
	
	.port-distance {
		font-size: 13px;
		color: #667eea;
		background: rgba(102, 126, 234, 0.1);
		padding: 2px 8px;
		border-radius: 10px;
		margin-left: 10px;
	}
	
	.port-description {
		font-size: 14px;
		color: #888888;
		line-height: 1.4;
	}
	
	.port-actions {
		display: flex;
		align-items: center;
		gap: 10px;
	}
	
	.port-arrow {
		font-size: 18px;
		color: #6c757d;
		cursor: pointer;
		padding: 5px;
		
		&:active {
			color: #667eea;
		}
	}
}

/* 空状态样式 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px 20px;
	text-align: center;
	
	.empty-icon {
		font-size: 48px;
		margin-bottom: 16px;
		opacity: 0.6;
	}
	
	.empty-text {
		font-size: 16px;
		color: #333333;
		font-weight: 500;
		margin-bottom: 8px;
	}
	
	.empty-desc {
		font-size: 14px;
		color: #888888;
		line-height: 1.4;
	}
}

/* 收藏按钮样式 */
.favorite-btn {
	width: 30px;
	height: 30px;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.2s ease;
	
	&.active {
		background: #ffd700; /* 金色 */
		box-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
	}
	
	.favorite-icon {
		font-size: 18px;
		color: #333333;
	}
}

/* 收藏港口弹框样式 */
.favorites-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.6);
	display: flex;
	align-items: flex-end;
	justify-content: center;
	z-index: 300;
	animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
	from {
		opacity: 0;
	}
	to {
		opacity: 1;
	}
}

.favorites-modal .modal-content {
	background: #ffffff;
	border-radius: 20px 20px 0 0;
	width: 100%;
	max-height: 70vh;
	overflow: hidden;
	box-shadow: 0 -10px 30px rgba(0, 0, 0, 0.2);
	animation: slideUpModal 0.3s ease-out;
}

.favorites-modal .modal-header {
	background: #f8f9fa;
}

.favorites-modal .modal-title {
	color: #333333;
}

.favorites-modal .port-item {
	padding: 16px 0;
	border-bottom: 1px solid #f0f0f0;
	transition: all 0.2s ease;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: rgba(102, 126, 234, 0.05);
		transform: scale(0.98);
	}
	
	.port-info {
		flex: 1;
	}
	
	.port-main {
		display: flex;
		justify-content: space-between;
		align-items: baseline;
		margin-bottom: 6px;
	}
	
	.port-name {
		font-size: 17px;
		font-weight: 500;
		color: #333333;
	}
	
	.port-distance {
		font-size: 13px;
		color: #667eea;
		background: rgba(102, 126, 234, 0.1);
		padding: 2px 8px;
		border-radius: 10px;
		margin-left: 10px;
	}
	
	.port-description {
		font-size: 14px;
		color: #888888;
		line-height: 1.4;
	}
	
	.port-arrow {
		font-size: 18px;
		color: #6c757d;
		margin-left: 15px;
	}
}

.favorites-modal .empty-state {
	padding: 60px 20px;
}

.favorites-modal .empty-icon {
	font-size: 48px;
	margin-bottom: 16px;
	opacity: 0.6;
}

.favorites-modal .empty-text {
	font-size: 16px;
	color: #333333;
	font-weight: 500;
	margin-bottom: 8px;
}

.favorites-modal .empty-desc {
	font-size: 14px;
	color: #888888;
	line-height: 1.4;
}


</style> 